/**
 * 深拷贝
 */
export function deepClone(obj) {
  if (obj === null) return null
  if (typeof obj === 'function') return cloneFunction(obj)
  if (typeof obj !== 'object') return obj
  if (obj instanceof RegExp) return new RegExp(obj)
  if (obj instanceof Date) return new Date(obj)
  const obj2 = new obj.constructor()
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      obj2[key] = deepClone(obj[key])
    }
  }
  return obj2
}

// 封装function拷贝方法
function cloneFunction() {
  const obj = [].shift.call(arguments)
  const temp = function temporary() {
    return obj.apply(this, arguments)
  }
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      temp[key] = obj[key]
    }
  }
  return temp
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat, fill = true) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return fill ? value.toString().padStart(2, '0') : value.toString()
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 判断值是否为空
 */
export function isEmpty(val) {
  if (val === null || val === '' || val === undefined) {
    return '--'
  } else {
    return val
  }
}

/**
 * 检查对象数组是否有重复 (当对象的属性名 顺序一致时)
 */
export function hasDuplicates(arr) {
  const seen = new Set()
  return arr.some((item) => {
    const itemString = JSON.stringify(item)
    if (seen.has(itemString)) {
      return true
    } else {
      seen.add(itemString)
      return false
    }
  })
}

/**
 * 数组转为树级结构
 * @param {Array}
 * @param {Object} 可配置参数
 * @returns {Array}
 */
export function arrayToTree(
  list,
  {
    rootId = null,
    idName = 'id',
    parentIdName = 'parentId',
    childName = 'children',
    initNull = true,
  } = {}
) {
  if (!Array.isArray(list)) {
    new Error('只能传入数组')
    return list
  }
  const itemMap = {} //
  const result = [] // 存放结果集
  for (const item of list) {
    const id = item[idName]
    const parentId = item[parentIdName]

    if (!itemMap[id]) {
      itemMap[id] = {
        [childName]: [],
      }
    }

    itemMap[id] = {
      ...item,
      [childName]: itemMap[id][childName],
    }

    const treeItem = itemMap[id]

    if (parentId === rootId) {
      result.push(treeItem)
    } else {
      if (!itemMap[parentId]) {
        itemMap[parentId] = {
          [childName]: [],
        }
      }

      itemMap[parentId][childName].push(treeItem)
    }
  }
  // 将 children 赋值为null
  if (initNull) {
    for (const key in itemMap) {
      if (!itemMap[key][childName].length) {
        itemMap[key][childName] = null
      }
    }
  }

  return result
}

/**
 *  树级结构转为一维数组
 * @param {Array}
 * @param {Object} 可配置参数
 * @returns {Array}
 */
export function treeToArray(treeArray, { childName = 'children' } = {}) {
  const stack = [].concat(treeArray) // 声明栈，用来存储待处理元素
  const result = [] // 接收结果
  // stack.push(obj) // 将初始元素压入栈
  while (stack.length) {
    // 栈不为空则循环执行
    const item = stack[0] // 取出栈顶元素
    result.push(item) // 元素本身压入结果数组
    stack.shift() // 将当前元素弹出栈
    // 逻辑处理，如果当前元素包含子元素，则将子元素压入栈
    if (item[childName] && item[childName].length) {
      stack.push(...item[childName])
    }
  }
  return result
}

/**
 * 根据数组对象中的某个属性进行数组去重
 * @param {Array}
 * @param {String}
 * @returns {Array}
 */
export function uniqueArray(list = [], key) {
  const has = {}
  return list.reduce(function (arr, item) {
    !has[item[key]] && (has[item[key]] = true && arr.push(item))
    return arr
  }, [])
}

/**
 * 数级结构数据去除  空的 child
 *  @param {Array}
 * @param {String}
 * @returns {Array}
 */

export function clearNoDataChilds(
  arr = [],
  obj = {
    rootId: null,
    idName: 'id',
    parentIdName: 'parentId',
    childName: 'children',
    initNull: true,
  }
) {
  let list = treeToArray(arr)
  list = arrayToTree(list, obj)
  return list
}
